const { app, BrowserWindow, Menu, screen, ipcMain, dialog } = require('electron')
const isDev = require('electron-is-dev')
const menuTemplate = require('./src/menuTemplate')
const path = require('path')
const AppWindow = require('./src/AppWindow')
let mainWindow, settingWindow
const Store = require('electron-store')
const settingsStore = new Store({ name: 'Settings'})
const fileStore = new Store({'name': 'FilesData'})
const QiniuManager = require('./src/utils/QiniuManager');
const { off } = require('process')
// Menu.setApplicationMenu(null)
const createManager = () => {
    const acceesKey = settingsStore.get('accessKey')
    const secretKey = settingsStore.get('secretKey')
    const bucketName = settingsStore.get('bucketName')
    return new QiniuManager(acceesKey, secretKey, bucketName)
}
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
app.on('ready', () => {
    // let size = screen.getPrimaryDisplay().workAreaSize
    // let sWidth = size.width;
    // let sHeight = size.height;
    const mainConfig = {
        icon: path.join(__dirname, 'public' , 'favicon.ico'),
        minWidth: 1240,
        minHeight: 800,
    }
    const urlLocation = isDev ? 'http://localhost:3000' : ''
    mainWindow = new AppWindow(mainConfig, urlLocation)
    mainWindow.on('closed', () => {
        mainWindow = null
    })
    ipcMain.on('upload-all-to-qiniu', () => {
        const manager = createManager()
        mainWindow.webContents.send('loading-status', true)
        const filesObj = fileStore.get('files') || {}
        const uploadPromiseArr = Object.keys(filesObj).map(key => {
            const file = filesObj[key]
            return manager.uploadFile(`${file.title}.txt`, file.path)
        })
        Promise.all(uploadPromiseArr).then(result => {
            console.log(result)
            dialog.showMessageBox({
                type: 'info',
                'message': '成功',
                title: '成功上传'
            })
            mainWindow.webContents.send('files-uploaded')
        }).catch (() => {
            dialog.showErrorBox('同步失败','请检查参数', err)
        }).finally(() => {
            mainWindow.webContents.send('loading-status', false)
        }) 
        
    })
    ipcMain.on('download-file', (event, data) => {
        const manager = createManager()
        const filesObj = fileStore.get('files')
        const { key, path , id } = data
        manager.getStat(data.key).then(resp => {
            const serverUpdatedTime = Math.round(resp.putTime / 10000)
            console.log('qiniu', serverUpdatedTime)
            const localUpdatedTime = filesObj[id].updatedAt
            console.log('local', localUpdatedTime)
            if( serverUpdatedTime > localUpdatedTime || !localUpdatedTime) {
                manager.downLoadFile(key, path).then(() => {
                    mainWindow.webContents.send('file-downloaded', {
                        status: 'download-success',
                        id
                    })
                })
            } else{
                mainWindow.webContents.send('file-downloaded', {
                    status: 'no-new-file',
                    id
                })
            }
        }, err => {
            console.log(err)
            if(err.statusCode == 612) {
                mainWindow.webContents.send('file-downloaded', {
                    status: 'no-file'
                })
            }
        })
    })
    ipcMain.on('upload-file', (event, data) => {
        const manager = createManager()
        manager.uploadFile(data.key, data.path).then(data => {
            mainWindow.webContents.send('active-file-uploaded')
        }).catch((err) => {
            dialog.showErrorBox('同步失败','请检查参数', err)
        })
    })
    ipcMain.on('open-settings-window', () => {
        const settingsWindowConfig = {
            icon: path.join(__dirname, 'public' , 'favicon.ico'),
            width: 500,
            height: 400,
            resizable: false,
            parent: mainWindow,
            autoHideMenuBar: true
        } 
        const settingsFileLocation = `file://${path.join(__dirname,'./settings', 'settings.html')}`
        settingWindow = new AppWindow(settingsWindowConfig, settingsFileLocation)
        settingWindow.on('closed', () => {
            settingWindow = null
        })
        settingWindow.webContents.openDevTools()
    })
    ipcMain.on('config-is-saved', () => {
        let qiniuMenu = process.platform == 'darwin' ? menu.items[3] : menu.items[2]
        const switchItems = (toggle) => {
            [1,2,3].forEach(number => {
                qiniuMenu.submenu.items[number].enabled = toggle 
            })
        }
        const qiniuIsConfiged =  ['accessKey', 'secretKey', 'bucketName'].every(key => !!settingsStore.get(key))
        if(qiniuIsConfiged) {
            switchItems(true)
        } else{
            switchItems(false)
        }
    })
    // 怎么让窗口始终保持在所有最前面
    // mainWindow.setAlwaysOnTop(true, 'screen');
    const menu = Menu.buildFromTemplate(menuTemplate)
    Menu.setApplicationMenu(menu)
    mainWindow.webContents.openDevTools()
})